package jmind.core.manager;

import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.FutureTask;

import jmind.core.lang.IProperties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class AbstractManager<T> {

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    public AbstractManager() {
        releaseResource();
    }

    protected final ConcurrentMap<String, FutureTask<T>> RESOURCES = new ConcurrentHashMap<String, FutureTask<T>>();

    public T getResource(final String name) {
        FutureTask<T> task = RESOURCES.get(name);
        if (task == null) {
            FutureTask<T> newTask = new FutureTask<T>(new Callable<T>() {
                @Override
                public T call() throws Exception {

                    return create(name);
                }
            });
            task = RESOURCES.putIfAbsent(name, newTask);
            if (task == null) {
                task = newTask;
                task.run();
            }
        }
        try {
            return task.get();
        } catch (Exception e) {
            logger.error("", e);
            return null;
        }

    }

    /**
     * 创建实例方法
     * 2013-7-19 
     * @param name
     * @return
     */
    public abstract T create(String name);

    /**
     * 获得配置
     * 2013-7-19 
     * @return
     */
    public abstract IProperties getProperties();

    public abstract void releaseResource();

}
